/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package gui;


import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JLabel;
import net.sourceforge.chart2d.Chart2DProperties;
import net.sourceforge.chart2d.Dataset;
import net.sourceforge.chart2d.GraphChart2DProperties;
import net.sourceforge.chart2d.GraphProperties;
import net.sourceforge.chart2d.LBChart2D;
import net.sourceforge.chart2d.LegendProperties;
import net.sourceforge.chart2d.MultiColorsProperties;
import net.sourceforge.chart2d.Object2DProperties;

/**
 *
 * @author bob
 */
public class Utilities extends javax.swing.JFrame {

    /**
     * Creates new form Utilities
     */ 
    Vector<String> months;
    public Utilities() {
        initComponents(); 
        months = new Vector<String>(12);
        months.add("January");
        months.add("February");
        months.add("March");
        months.add("April");
        months.add("May");
        months.add("June");
        months.add("July");
        months.add("August");
        months.add("September");
        months.add("October");
        months.add("November");
        months.add("December");
        DateFormat df = new SimpleDateFormat("yyyy/MM/dd");
        startDate.setDateFormat(df);
        endDate.setDateFormat(df);
        
       // Calendar now = Calendar.getInstance();
       // now.set(now.YEAR, now.MONTH+1, now.DATE);
       
       // endDate.setCurrent(now);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        graphChart2DProperties1 = new net.sourceforge.chart2d.GraphChart2DProperties();
        graphBox = new javax.swing.JPanel();
        imageLabel = new javax.swing.JLabel();
        jPanel2 = new javax.swing.JPanel();
        startLabel = new javax.swing.JLabel();
        endLabel = new javax.swing.JLabel();
        searchByLabel = new javax.swing.JLabel();
        aptNumBox = new javax.swing.JTextField();
        showButton = new javax.swing.JButton();
        backButton = new javax.swing.JButton();
        startDate = new datechooser.beans.DateChooserCombo();
        endDate = new datechooser.beans.DateChooserCombo();
        typeBox = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.EXIT_ON_CLOSE);

        graphBox.setBackground(new java.awt.Color(255, 255, 255));

        javax.swing.GroupLayout graphBoxLayout = new javax.swing.GroupLayout(graphBox);
        graphBox.setLayout(graphBoxLayout);
        graphBoxLayout.setHorizontalGroup(
            graphBoxLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(imageLabel, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
        );
        graphBoxLayout.setVerticalGroup(
            graphBoxLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addComponent(imageLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 407, Short.MAX_VALUE)
        );

        jPanel2.setBorder(javax.swing.BorderFactory.createTitledBorder(null, "Options", javax.swing.border.TitledBorder.DEFAULT_JUSTIFICATION, javax.swing.border.TitledBorder.DEFAULT_POSITION, new java.awt.Font("Tahoma", 0, 14))); // NOI18N
        jPanel2.setRequestFocusEnabled(false);

        startLabel.setText("Start Date:");

        endLabel.setHorizontalAlignment(javax.swing.SwingConstants.RIGHT);
        endLabel.setText("End Date:");

        searchByLabel.setText("Apartment Number:");

        showButton.setText("Show");
        showButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                showButtonMouseClicked(evt);
            }
        });

        backButton.setText("Back");
        backButton.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                backButtonMouseClicked(evt);
            }
        });

        startDate.setCurrentView(new datechooser.view.appearance.AppearancesList("Swing",
            new datechooser.view.appearance.ViewAppearance("custom",
                new datechooser.view.appearance.swing.SwingCellAppearance(new java.awt.Font("Tahoma", java.awt.Font.PLAIN, 11),
                    new java.awt.Color(0, 0, 0),
                    new java.awt.Color(0, 0, 255),
                    false,
                    true,
                    new datechooser.view.appearance.swing.ButtonPainter()),
                new datechooser.view.appearance.swing.SwingCellAppearance(new java.awt.Font("Tahoma", java.awt.Font.PLAIN, 11),
                    new java.awt.Color(0, 0, 0),
                    new java.awt.Color(0, 0, 255),
                    true,
                    true,
                    new datechooser.view.appearance.swing.ButtonPainter()),
                new datechooser.view.appearance.swing.SwingCellAppearance(new java.awt.Font("Tahoma", java.awt.Font.PLAIN, 11),
                    new java.awt.Color(0, 0, 255),
                    new java.awt.Color(0, 0, 255),
                    false,
                    true,
                    new datechooser.view.appearance.swing.ButtonPainter()),
                new datechooser.view.appearance.swing.SwingCellAppearance(new java.awt.Font("Tahoma", java.awt.Font.PLAIN, 11),
                    new java.awt.Color(128, 128, 128),
                    new java.awt.Color(0, 0, 255),
                    false,
                    true,
                    new datechooser.view.appearance.swing.LabelPainter()),
                new datechooser.view.appearance.swing.SwingCellAppearance(new java.awt.Font("Tahoma", java.awt.Font.PLAIN, 11),
                    new java.awt.Color(0, 0, 0),
                    new java.awt.Color(0, 0, 255),
                    false,
                    true,
                    new datechooser.view.appearance.swing.LabelPainter()),
                new datechooser.view.appearance.swing.SwingCellAppearance(new java.awt.Font("Tahoma", java.awt.Font.PLAIN, 11),
                    new java.awt.Color(0, 0, 0),
                    new java.awt.Color(255, 0, 0),
                    false,
                    false,
                    new datechooser.view.appearance.swing.ButtonPainter()),
                (datechooser.view.BackRenderer)null,
                false,
                true)));
    startDate.setWeekStyle(datechooser.view.WeekDaysStyle.FULL);

    typeBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Electric", "Gas" }));

    jLabel1.setText("Type:");

    javax.swing.GroupLayout jPanel2Layout = new javax.swing.GroupLayout(jPanel2);
    jPanel2.setLayout(jPanel2Layout);
    jPanel2Layout.setHorizontalGroup(
        jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel2Layout.createSequentialGroup()
            .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addComponent(showButton, javax.swing.GroupLayout.PREFERRED_SIZE, 90, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addGap(165, 165, 165)
            .addComponent(backButton)
            .addContainerGap())
        .addGroup(jPanel2Layout.createSequentialGroup()
            .addGap(92, 92, 92)
            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addComponent(startLabel)
                .addComponent(jLabel1))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addComponent(startDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addComponent(endLabel, javax.swing.GroupLayout.DEFAULT_SIZE, 66, Short.MAX_VALUE))
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addComponent(typeBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(searchByLabel)))
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addComponent(endDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addComponent(aptNumBox, javax.swing.GroupLayout.PREFERRED_SIZE, 81, javax.swing.GroupLayout.PREFERRED_SIZE))
            .addGap(66, 66, 66))
    );
    jPanel2Layout.setVerticalGroup(
        jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(jPanel2Layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addComponent(endDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addGap(18, 18, 18)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(aptNumBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(searchByLabel))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addComponent(backButton))
                .addGroup(jPanel2Layout.createSequentialGroup()
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addComponent(endLabel)
                        .addComponent(startLabel)
                        .addComponent(startDate, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGap(18, 18, 18)
                    .addGroup(jPanel2Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(typeBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel1))
                    .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                    .addComponent(showButton, javax.swing.GroupLayout.PREFERRED_SIZE, 34, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap())))
    );

    javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
    getContentPane().setLayout(layout);
    layout.setHorizontalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
            .addContainerGap()
            .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addComponent(graphBox, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
            .addContainerGap())
    );
    layout.setVerticalGroup(
        layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
        .addGroup(layout.createSequentialGroup()
            .addContainerGap()
            .addComponent(graphBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
            .addComponent(jPanel2, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
            .addContainerGap())
    );

    pack();
    }// </editor-fold>//GEN-END:initComponents

    private void showButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_showButtonMouseClicked
        try {
            //DateFormat dateFormat = new DateFormat();
             /*
             Calendar start = new GregorianCalendar();
             Calendar end =  new GregorianCalendar(); 
             
             int startMonth, startDay, startYear;
             int endMonth, endDay, endYear;
             
             
           
             //initialize start date
             String dateString = startDate.getText();
             System.out.println(startDate.getText());
            // dateString.replace(",", "");
             String[] dateArray = new String[3];
             dateArray = dateString.split("/");
             startMonth = Integer.parseInt(dateArray[0]);
             startDay = Integer.parseInt(dateArray[1]);
             startYear = Integer.parseInt(dateArray[2]);      
             start.set(startYear, startMonth, startDay);
             
             //initialize end date
             dateString = endDate.getText();
             dateString.replace(",", "");      
             dateArray = dateString.split("/");
             endMonth = Integer.parseInt(dateArray[0]);
             endDay = Integer.parseInt(dateArray[1]);
             endYear = Integer.parseInt(dateArray[2]); 
             
             System.out.println(endYear+" "+ endMonth+ " "+ endDay);
             end.set(endYear, endMonth, endDay);
             
             System.out.println("MONTHS:"+(end.getTimeInMillis() - start.getTimeInMillis())/86400000/30);
             //long numMonths = (end.getTimeInMillis() - start.getTimeInMillis())/86400000/30;
             int numMonths = 3;
             * */
           String start = startDate.getText();
           String end = endDate.getText();
           
           DBconnection db = new DBconnection();
           Connection conn = db.getConnection();
           
           String query = "SELECT DATEDIFF(?, ?)";
           PreparedStatement statement = conn.prepareStatement(query);
           
           statement.setString(1, end);
           statement.setString(2, start);
           
           ResultSet rs = statement.executeQuery();        

           int numMonths = 1;
       
           while (rs.next()) 
           {
               System.out.println("GETTING MONTHS");
                
               numMonths = rs.getInt(1);
               System.out.println(rs.getInt(1));
                
                //System.out.println("");  
          }
           numMonths /= 30;
          //  conn.close();
          // statement.close();
           if(numMonths < 1)
           {
               numMonths = 1;
           }
           System.out.println("NUMMONTHS = "+ numMonths);
           int startMonth = Integer.parseInt(startDate.getText().substring(5, 7));
           int endMonth = Integer.parseInt(endDate.getText().substring(5, 7));
           
           System.out.println("START MONTH:" + startMonth);
            
           Object2DProperties object2DProps = new Object2DProperties();
           object2DProps.setObjectTitleText ("Utility Usage");
           
           Chart2DProperties chart2DProps = new Chart2DProperties();
           
           
           
           LegendProperties legendProps = new LegendProperties();
           legendProps.setLegendLabelsTexts (new String[] {"Apt", "Average"});


          // legendProps.setLegendExistence (false); 
           //legendProps
           
           GraphChart2DProperties graph2DProps = new GraphChart2DProperties();
           String[] labels = {"January", "February", "March", "April", "May",
                               "June", "July", "August", "September", "October",
                               "November", "December"};
           String[] usedLabels = new String[numMonths];
           int monthLabelCounter = startMonth-1;
                      
           String aptNum = aptNumBox.getText();
           String type = typeBox.getSelectedItem().toString();
           query = "SELECT AMOUNT FROM MONTHLYUSAGE WHERE USEDATE BETWEEN ? AND ? AND APTNO = ? AND KIND = ? ORDER BY USEDATE";
           statement = conn.prepareStatement(query);
           
           statement.setString(1, start);
           statement.setString(2, end);
           statement.setString(3, aptNum);   
           statement.setString(4, type);
           
           rs = statement.executeQuery(); 
      
           ResultSetMetaData rsmd = rs.getMetaData();
          
           int numColumns = rsmd.getColumnCount();
           System.out.println("NUMCOLUMNS: "+ numColumns);
           
            //System.out.println(numMonths);
           float[] values = new float[numMonths];
           //values[0] = 510;
          // values[1] = 520;
          // values[2] = 550;
           //values[3] = 540;
           float[] avgValues = new float[numMonths];
           //avgValues[0] = 530;
          // avgValues[1] = 530;
          // avgValues[2] = 540;
          // avgValues[3] = 556;
           
           int count = 0;
           while (rs.next()) 
           {                  
                  float data = rs.getFloat(1);
                  System.out.println("DATA: "+data);
                  values[count] = data;
                  count++;                               //System.out.println("");  
          }
           
           query = "SELECT AVG(AMOUNT) FROM MONTHLYUSAGE WHERE USEDATE BETWEEN ? AND ? AND KIND = ? GROUP BY MONTH(USEDATE) ORDER BY USEDATE";
           statement = conn.prepareStatement(query);
           
           statement.setString(1, start);
           statement.setString(2, end);
           statement.setString(3, type);             
           rs = statement.executeQuery();       
           rsmd = rs.getMetaData();
           numColumns = rsmd.getColumnCount();
           
           count = 0;
           while (rs.next()) 
           {                  
                  float data = rs.getFloat(1);
                  System.out.println("AVGDATA: "+data);
                  avgValues[count] = data;
                  count++;
                               //System.out.println("");  
          }
           
           conn.close();
           statement.close();         
           GraphProperties graphProps = new GraphProperties();
           Dataset dataset = new Dataset (2, numMonths, 1);
           
           System.out.println("LENGTH= "+values.length);
           for(int i = 0; i < values.length; i++)
           {        
               dataset.set (0, i, 0, values[i]);  //where data1 is your first value (ex. 23f)           
               dataset.set (1, i, 0, avgValues[i]);  //where data1 is your first value (ex. 23f)   
               usedLabels[i] = labels[monthLabelCounter];
               monthLabelCounter++;
               monthLabelCounter = monthLabelCounter%12;
               System.out.println("INSERTING "+ values[i]);
           } 
           
           graph2DProps.setLabelsAxisLabelsTexts(usedLabels);
           graph2DProps.setLabelsAxisTitleText("Month");
           graph2DProps.setNumbersAxisTitleText("kwH");
           
           MultiColorsProperties multiColorsProps = new MultiColorsProperties();
           graphProps.setGraphBarsExistence (false);
           graphProps.setGraphLinesExistence (true);
           graphProps.setGraphDotsExistence(true);

           LBChart2D lbChart2D = new LBChart2D();
           lbChart2D.setObject2DProperties (object2DProps);
           lbChart2D.setChart2DProperties (chart2DProps);
           lbChart2D.setLegendProperties (legendProps);
           lbChart2D.setGraphChart2DProperties (graph2DProps);
           lbChart2D.addGraphProperties (graphProps);
           lbChart2D.addDataset (dataset);
           lbChart2D.addMultiColorsProperties (multiColorsProps);
           
           lbChart2D.setSize(648, 408);
           lbChart2D.setPreferredSize(new Dimension(648,408));
          // lbChart2D.pack();
           
           BufferedImage lbImage = lbChart2D.getImage();
           
           ImageIcon icon = new ImageIcon(lbImage);        
           imageLabel.setIcon(icon);     
        } catch (SQLException ex) {
            Logger.getLogger(Utilities.class.getName()).log(Level.SEVERE, null, ex);
        }
                
    }//GEN-LAST:event_showButtonMouseClicked

    private void backButtonMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_backButtonMouseClicked
        //create main window
        MainMenu main = new MainMenu();
        main.setLocation(MainMenu.X, MainMenu.Y);
        main.setVisible(true);
                
        //close this window
        this.dispose(); 
    }//GEN-LAST:event_backButtonMouseClicked

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JTextField aptNumBox;
    private javax.swing.JButton backButton;
    private datechooser.beans.DateChooserCombo endDate;
    private javax.swing.JLabel endLabel;
    private javax.swing.JPanel graphBox;
    private net.sourceforge.chart2d.GraphChart2DProperties graphChart2DProperties1;
    private javax.swing.JLabel imageLabel;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel jPanel2;
    private javax.swing.JLabel searchByLabel;
    private javax.swing.JButton showButton;
    private datechooser.beans.DateChooserCombo startDate;
    private javax.swing.JLabel startLabel;
    private javax.swing.JComboBox typeBox;
    // End of variables declaration//GEN-END:variables
}
